from django.shortcuts import render
from rest_framework.views import APIView
from .models import Area
from rest_framework.response import Response
from rest_framework import status
from .serializers import AreaSerializer, SubsSerializer
from rest_framework_extensions.cache.decorators import cache_response

# Create your views here.
class AreaListView(APIView):
    """查询所有省"""
    @cache_response(timeout=60*60,cache='default')
    def get(self, request):
        qs = Area.objects.filter(parent=None)
        serializer = AreaSerializer(qs, many=True)
        return Response(serializer.data)


class AreaDetailView(APIView):
    """查询单一省或市"""

    @cache_response(timeout=60 * 60, cache='default')
    def get(self, request, pk):
        try:
            area = Area.objects.get(id=pk)
        except Area.DoesNotExist:
            return Response({'message': '无效的pk'}, status=status.HTTP_400_BAD_REQUEST)
        serializer = SubsSerializer(area)
        return Response(serializer.data)
